package com.practice.datasource;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DBCPDataSource extends DataSource{
    private final List<Connection> pool = new ArrayList<>();
    private final String url = SQLConstant.URL;
    private final String user = SQLConstant.USER;
    private final String password = SQLConstant.PASSWORD;

    public DBCPDataSource(int initialSize) throws SQLException {
        initializePool(initialSize);
    }

    private void initializePool(int initialSize) throws SQLException {
        for(int i=0 ; i < initialSize ; i++){
            Connection realConn = DriverManager.getConnection(url,user,password);
            Connection proxyConn = (Connection) Proxy.newProxyInstance(
                    Connection.class.getClassLoader(),
                    new Class[]{Connection.class},
                    new ConnectionHandler(realConn,this)
            );
            pool.add(proxyConn);
        }
    }

    @Override
    public synchronized Connection getConnection() throws SQLException {
        if(!pool.isEmpty()){
            return pool.remove(0);
        }

        Connection realConn = DriverManager.getConnection(url,user,password);
        return (Connection) Proxy.newProxyInstance(
                Connection.class.getClassLoader(),
                new Class[]{Connection.class},
                new ConnectionHandler(realConn,this)
        );
    }

    synchronized void returnConnection(Connection connection){
        pool.add(connection);
    }
}
